package autohome.wz.job;

import autohome.wz.lib.AutoHomeNewsHelper;
import autohome.wz.lib.Common;
import autohome.wz.lib.HttpRequest;
import autohome.wz.model.AutoHomeNews;
import autohome.wz.model.BaseApiResult;
import autohome.wz.model.KouBei.KouBeiDetailResult;
import autohome.wz.model.KouBei.KouBeiImage;
import autohome.wz.model.KouBei.KouBeiItem;
import autohome.wz.model.KouBei.KouBeiResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author lixin
 */
public class KouBeiJob implements Job {
    private static Logger logger = Logger.getLogger(KouBeiJob.class);
    private static String kouBeiApi = "http://koubeidata.in.autohome.com.cn/api/feed/GetAllFeedRecommend?_appid=wz&timestamp=2015-1-1&pageindex=%d&pagesize=20";
    private static String kouBeiDetailApi = "https://koubei.app.autohome.com.cn/autov8.5.5/alibi/NewEvaluationInfo.ashx?eid=%d&isNoCache=1";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        init();
    }

    public static void main(String[] args0) {
        //init();
        logger.info("koubei");
    }

    private void init() {
        int pageIndex = 1;
        int pageCount = 10000;
        int totalAmount = 0;
        try {
            while (pageIndex <= pageCount) {
                String apiResult = HttpRequest.sendGet(String.format(kouBeiApi, pageIndex), "");
                if (apiResult.length() > 0) {
                    Gson gson = new Gson();
                    BaseApiResult<KouBeiResult> kouBeiResultList = gson.fromJson(apiResult, new TypeToken<BaseApiResult<KouBeiResult>>() {
                    }.getType());
                    if (kouBeiResultList != null) {
                        KouBeiResult kouBeiResult = kouBeiResultList.getResult();

                        for (KouBeiItem topicItem : kouBeiResult.getTopiclist()) {
                            AutoHomeNews model = new AutoHomeNews();
                            if (topicItem.getTitle() == null || topicItem.getTitle().equals("")) {
                                System.out.println(topicItem.getBiz_id() + "||pageIndex:" + pageIndex);
                                continue;
                            }
                            model.setTitle(topicItem.getTitle());
                            model.setContent(topicItem.getContent());
                            model.setBiz_id(topicItem.getBiz_id());
                            model.setBiz_type(topicItem.getBiz_type());
                            model.setCms_series_id(topicItem.getCms_series_id());
                            model.setCms_tags(topicItem.getCms_tags());
                            model.setCms_content_class(topicItem.getCms_tags());
                            model.setIndex_detail("");
                            model.setAuthor(topicItem.getAuthor());
                            model.setImg_url("");
                            model.setCheckStatus(3);

                            //调用详情接口获取图片列表
                            List<String> imageList = getImageList(model.getBiz_id());
                            if (imageList.size() > 0) {
                                model.setImg_url(imageList.get(0));
                                if (imageList.size() >= 3) {
                                    model.setGraphic_img_list2(String.join(",", imageList.subList(0, 3)));
                                } else {
                                    model.setGraphic_img_list2("");
                                }
                            }
                            if (topicItem.getRecommend_time() != null) {
                                model.setPublish_time(Common.GetSqlTimeSpan(topicItem.getPublish_time()));
                            }
                            if (AutoHomeNewsHelper.Add(model) > 0) {
                                Common.showMessage(topicItem.getTitle() + "入库成功");
                                totalAmount++;
                            }
                        }
                        if (kouBeiResult.getRowcount() > 0) {
                            pageCount = kouBeiResult.getRowcount() / 20 + 1;
                            System.out.println("pageCount=" + pageCount);
                        }
                    }
                    pageIndex++;
                }
            }
            Common.showMessage("一共入库数据=" + totalAmount);
        } catch (ParseException e) {
            logger.error("Init:" + e.getMessage());
        }
    }

    private List<String> getImageList(long bizId) {
        List<String> imageStrList = new ArrayList();
        try {
            String detailResult = HttpRequest.sendGet(String.format(kouBeiDetailApi, bizId), "");
            if (detailResult.length() > 0) {
                Gson gson = new Gson();
                BaseApiResult<KouBeiDetailResult> kouBeiDetailResult = gson.fromJson(detailResult, new TypeToken<BaseApiResult<KouBeiDetailResult>>() {
                }.getType());
                if (kouBeiDetailResult != null) {
                    List<KouBeiImage> imageList = kouBeiDetailResult.getResult().getKoubeiphotos();
                    for (KouBeiImage imageData : imageList) {
                        String imageUrl = imageData.getUrl();
                        if (imageUrl != null && !imageUrl.equals("")) {
                            imageStrList.add(imageData.getUrl());
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("getImageList:" + e.getMessage());
        }

        return imageStrList;
    }

}
